package leetcode.t2String;

import java.util.HashMap;

/**
 * 3. 无重复字符的最长子串
 * 滑动窗口，记录不重复的元素，left记录窗口开始的下标位置
 *
 * @author K
 * @date 2024/1/23 14:02
 */
public class T3_LengthOfLongestSubstring {

    public static int lengthOfLongestSubstring(String s) {
        //left记录窗口开始的下标位置
        int result = 0, left = 0;
        HashMap<Character, Integer> map = new HashMap<>();
        char[] chars = s.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            if (map.containsKey(chars[i])) {
                //更新窗口开始的下标位置
                left = Math.max(left, map.get(chars[i]) + 1);
            }
            map.put(chars[i], i);
            result = Math.max(result, i - left + 1);
        }

        return result;
    }

    public static void main(String[] args) {
        int result = lengthOfLongestSubstring("abcabcbb");
        int result1 = lengthOfLongestSubstring("bbbbb");
        int result2 = lengthOfLongestSubstring("pwwkew");
        int result3 = lengthOfLongestSubstring("a");
        System.out.println();
    }
}
